import random
import string

from django.contrib.auth.models import User, Group
from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.status import HTTP_404_NOT_FOUND
from rest_framework.viewsets import ModelViewSet, ViewSet

from users.serializers import CreateUserSerializer
from .models import Classes
from .serializers import ClassesSerializer
from rest_framework.permissions import IsAuthenticated
from users.utils import Mypermission
from celery_tasks.email.tasks import send_mail_task


class ClassesViewSet(ModelViewSet):
    # 设置局部权限 IsAuthenticated 登录才有操作权限
    # permission_classes = [IsAuthenticated]
    permission_classes = [Mypermission]  # 使用自定义权限

    queryset = Classes.objects.filter(is_delete=False)
    serializer_class = ClassesSerializer


class ClassesMemberViewSet(ViewSet):  # 这个视图我们只需要做注册这一件事
    permission_classes = [Mypermission]
    serializer_class = CreateUserSerializer

    def add_member(self, request, pk):
        # 获取班级
        try:
            classes = Classes.objects.get(id=pk,is_delete=False)
        except Classes.DoesNotExist:
            return Response(status=HTTP_404_NOT_FOUND)
        # 判断该成员是否已属于该班级
        username = request.data['username']
        member = classes.member.filter(username=username)  # 多表查询， 多对多查询 classes.member.filter() 获取该班级指定用户名的学生
        # 属于，返回提示
        if member:
            return Response({'msg': '该成员已加入该班级'})
        # 不属于，判断是否注册，是否存在该用户
        user = User.objects.filter(username=username)
        if user:
            # 存在，添加到该班级
            classes.member.add(user[0])  # user是一个查询集，需要索引取值
            return Response(CreateUserSerializer(user[0]).data)

        # 不存在，注册用户，并添加学生身份，添加到班级
        userserializer = CreateUserSerializer(data=request.data)  # 反序列化
        userserializer.is_valid(raise_exception=True)

        email = request.data['email']
        first_name = request.data['first_name']
        user = User(username=username, email=email, first_name=first_name)

        # 生成初始化密码
        source = string.ascii_letters + string.digits
        password = ''.join(random.sample(source, 6))
        # 这里为什么不用user.password=password，因为我们希望存储在数据库里的密码是加密的
        # set_password方法能帮助我们进行加密
        user.set_password(password)
        user.save()

        # 并添加学生身份
        group = Group.objects.get(id=1)  # 拿到学生组
        group.user_set.add(user)  # 反向添加，用user_set管理器

        # 添加到班级
        classes.member.add(user)

        # 使用celery.  发送短信验证码 .delay是异步调，去掉就是同步调
        send_mail_task.delay(email, user.username, password, classes.name)

        return Response(userserializer.data)
